// pages/backMessage/backMessage.js
var util = require("../../utils/util.js");
const APP = getApp()
const date = new Date()
const nowYear = date.getFullYear()
const nowMonth = date.getMonth() + 1
const nowDay = date.getDate()
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
let getDays = function (year, month) {
  if (month === 2) {
    return ((year % 4 === 0) && ((year % 100) !== 0)) || (year % 400 === 0) ? 29 : 28
  } else {
    return daysInMonth[month - 1]
  }
}
let getDays1 = function (year1, month1) {
  if (month1 === 2) {
    return ((year1 % 4 === 0) && ((year1 % 100) !== 0)) || (year1 % 400 === 0) ? 29 : 28
  } else {
    return daysInMonth[month1 - 1]
  }
}
// 根据年月日设置当前月有多少天 并更新年月日数组
let setDate = function (year, month, day, year1, month1, day1, _this) {
  let daysNum =  getDays(year, month)
  let days1Num =  getDays1(year1, month1)
  day = day > daysNum ? 1 : day
  day1 = day1 > days1Num ? 1 : day1
  let monthsNum = 12
  let months1Num =  12
  let years = []
  let months = []
  let days = []
  let yearIndex = 9999
  let monthIndex = 0
  let dayIndex = 0
  let years1 = []
  let months1 = []
  let days1 = []
  let year1Index = 9999
  let month1Index = 0
  let day1Index = 0
  // 重新设置年份列表
  for (let i = 1990; i <= 2300; i++) {
    years.push(i)
    years1.push(i)
  }
  years.map((v, idx) => {
    if (v === year) {
      yearIndex = idx
    }
  })
  years1.map((v, idx) => {
    if (v === year1) {
      year1Index = idx
    }
  })
  // 重新设置月份列表
  for (let i = 1; i <= monthsNum; i++) {
    var k = i;
    months.push(k)
    
  }
  months.map((v, idx) => {
    if (v === month) {
      monthIndex = idx
    }
  })
  for (let i = 1; i <= months1Num; i++) {
    var k = i;
    months1.push(k)

  }
  months1.map((v, idx) => {
    if (v === month1) {
      month1Index = idx
    }
  })
  // 重新设置日期列表
  for (let i = 1; i <= daysNum; i++) {
    var k = i;
    days.push(k)
  }
  days.map((v, idx) => {
    if (v === day) {
      dayIndex = idx
    }
  })
  for (let i = 1; i <= days1Num; i++) {
    var k = i;
    days1.push(k)
  }
  days1.map((v, idx) => {
    if (v === day1) {
      day1Index = idx
    }
  })
  _this.setData({
    //时间列表参数
    years: years,
    months: months,
    days: days,
    //选中的日期
    year: year,
    month: month,
    day: day,
    years1: years1,
    months1: months1,
    days1: days1,
    //选中的日期
    year1: year1,
    month1: month1,
    day1: day1,
    value: [yearIndex, monthIndex, dayIndex, year1Index, month1Index, day1Index],
  })
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    years: [],
    months: [],
    days: [],
    //选中的日期
    year: nowYear,
    month: nowMonth,
    day: nowDay,
    years1: [],
    months1: [],
    days1: [],
    //选中的日期
    year1: nowYear,
    month1: nowMonth,
    day1: nowDay,
    value: [9999, 1, 1, 9999, 1, 1],
    // years: [],
    // months: [],
    // days: [],
    // year: nowYear,
    // month: nowMonth,
    // day: nowDay,
    // value: [9999, 1, 1],
    //日期
    // years: years,
    // years1: years1,
    // year: date.getFullYear(),
    // year1: date.getFullYear(),
    // months: months,
    // months1: months1,
    // month: 2,
    // month1: 2,
    // days: days,
    // days1: days1,
    // day: 2,
    // day1: 2,
    // value: [9999, 1, 1, 9999, 1, 1],

    itemTitle: '选择日期',
    itemTitle1: '选择日期',
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    currentDate1: new Date().getTime(),
    minDate1: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    formatter1(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    num: 0,
    paramas: [],
    pageNum: 1,
    pageSize: 3,
    deptList: [],
    navList: [],
    temp: [],
    temp1: [],
    dateStart:date.toLocaleDateString().replace(/\//g,'-'),
    dateend: date.toLocaleDateString().replace(/\//g, '-'),
    time: "09:00",
    times: "09:00",
    index: 0,
    array: [30, 60],
    indexMornS: 0,
    indexMorE: 0,
    indexAftS: 0,
    indexAftE: 0,
    moriningStart: [
      '',
      '00:00',
      '00:30',
      '01:00',
      '01:30',
      '02:00',
      '02:30',
      '03:00',
      '03:30',
      '04:00',
      '04:30',
      '05:00',
      '05:30',
      '06:00',
      '06:30',
      '07:00',
      '07:30',
      '08:00',
      '08:30',
      '09:00',
      '09:30',
      '10:00',
      '10:30',
      '11:00',
      '11:30',
      '12:00'
    ],
    moriningEnd: [],
    afternoonStart: [
      '',
      '12:00',
      '12:30',
      '13:00',
      '13:30',
      '14:00',
      '14:30',
      '15:00',
      '15:30',
      '16:00',
      '16:30',
      '17:00',
      '17:30',
      '18:00',
      '18:30',
      '19:00',
      '19:30',
      '20:00',
      '20:30',
      '21:00',
      '21:30',
      '22:00',
      '22:30',
      '23:00',
      '23:30',
      '00:00'
    ],
    afternoonEnd: [],
    value1: '',
    value2: '',
    value3: '',
    value5: '',
    value6: '',
    value7: '',
    title: '',
    show5: false,
    showx:false,
    showt:false,
    showa: false,
  },
  value1:[0,0],
  value10: [0, 0],
  //日期
  sure: function (event) {
    var date = event.detail
    this.setData({
      pageNum: 1,
      pageSize: 4,
      'paramas.startTime':'',
      navList: [],
      itemTitle: util.js_date_time(date),
      'paramas.startTime': util.js_date_time(date)

    });
    this.getMessageList();
    this.selectComponent('#item').toggle();
  },

  close: function () {
    this.selectComponent('#item').toggle();
  },

  sure1: function (event) {
    var date = event.detail
    this.setData({
      pageNum: 1,
      pageSize: 4,
      'paramas.tagTime':'',
      navList: [],
      itemTitle1: util.js_date_time(date),
      'paramas.tagTime': util.js_date_time(date)

    });

    this.getMessageList();
    this.selectComponent('#item1').toggle();
  },

  close1: function () {
    this.selectComponent('#item1').toggle();
  },

  
  //监听input事件

  remark: function (e) {
    console.log(e.detail)
    this.setData({
      ['form.remark']: e.detail
    });

  },

  onClick: function () {
    this.setData({
      pageNum: 1,
      pageSize: 4,
      navList: []
    })
    this.getMessageList();
  },
  onChange(e) {

    this.setData({
      paramas: {
        deptName: e.detail,
      }
    });
  },
  onSearch() {
    this.setData({
      pageNum: 1,
      pageSize: 4,
      navList: []
    })
    // this.onShow();
    this.getMessageList();
  },
  //日期
  close2: function () {
    this.setData({
      showx: false,
      show: true,
    })
  },
  sure2:function(){
    // console.log(this.data.dateStart)
    // console.log(this.data.dateend)
     for(var i = 0 ;i<=1;i++){
       if( i == 0){
        var day = this.data.dateStart
       }
       if(i == 1){
        var day = this.data.dateend
       }
      //c处理日
      var index = day.lastIndexOf('-')
      var start = day.slice(0, index + 1)
      var end = day.slice(index + 1, day.length)
      if ((+end) < 10) end = '0' + end
      var newStr = start + end
      //处理月
      var firstIndex = day.indexOf('-')
      var newStart = day.slice(0, firstIndex + 1)
      var newEnd = day.slice(firstIndex + 1, index)
      if ((+newEnd) < 10) newEnd = '0' + newEnd
      var allStr = newStart + newEnd + '-' + end
      console.log(allStr)
      if(i==0){
        this.setData({
          ['form.timeDate']:allStr,
          // showx: false,
          // show: true,
          // ['form.timeDate1']: this.data.dateend,
        })
       }
       if(i==1){
        this.setData({
  
        
          ['form.timeDate1']: allStr,
        })
       }
     }
     
     this.setData({
      showx: false,
      show: true,
    })
   

    

  },
  showx() {
    this.setData({
      showx: true,
      show: false
    })
  },
 
  bindChange: function (e) {
    
    var date =this.data.dateStart
    var date1 =this.data.dateend
    const val = e.detail.value
    
    setDate(this.data.years[val[0]], this.data.months[val[1]], this.data.days[val[2]], this.data.years1[val[3]], this.data.months1[val[4]], this.data.days1[val[5]], this)
    console.log(val)
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]],
      year1: this.data.years1[val[3]],
      month1: this.data.months1[val[4]],
      day1: this.data.days1[val[5]],
    })
    date = this.data.year +'-'+this.data.month+'-'+this.data.day;
    date1 = this.data.year1 + '-' + this.data.month1 + '-' + this.data.day1;
    this.setData({
      dateStart:date,
      dateend:date1
    })
  },
//上午时间
  showt() {
    this.setData({
      showt: true,
      show: false
    })
  },
  close3: function () {
    this.setData({
      showt: false,
      show: true,
    })
  },
  sure3: function () {
   
    this.setData({
     
      showt: false,
      show: true,
      ['form.morningStartTime']: this.data.moriningStart[this.data.indexMornS],
      ['form.morningEndTime']: this.data.moriningEnd[this.data.indexMorE],
      
    })
  },
  bindChange1: function (e) {

    const val = e.detail.value
    const num = val[0]
    var end =[]

    for (var i = num + 1; i < this.data.moriningStart.length; i++)
      end.push(this.data.moriningStart[i])
      this.setData({
        moriningEnd: end,
    
      })
    this.setData({
      indexMornS: val[0] ,
      indexMorE: val[1] ,
    })
  },


  //下午时间
  showa() {
    this.setData({
      showa: true,
      show: false
    })
  },
  close4: function () {
    this.setData({
      showa: false,
      show: true,
    })
  },
  sure4: function () {

    this.setData({

      showa: false,
      show: true,
      ['form.afternoonStartTime']: this.data.afternoonStart[this.data.indexAftS],
      ['form.afternoonEndTime']: this.data.afternoonEnd[this.data.indexAftE],
    })
    console.log(this.data.form.afternoonEndTime)
  },
  bindChange2: function (e) {

    const val = e.detail.value
    const num = val[0]
    var end = []

    for (var i = num + 1; i < this.data.afternoonStart.length; i++)
      end.push(this.data.afternoonStart[i])
    this.setData({
     afternoonEnd: end,

    })
    this.setData({
      indexAftS: val[0],
      indexAftE: val[1],
    })
  },
  //日期数值变动
  // bindStartChange: function (e) {

  //   this.setData({
  //     dateStart: e.detail.value,
  //     ['form.timeDate']: e.detail.value,
  //   })

  // },

  // bindEndChange: function (e) {
  //   this.setData({
  //     dateend: e.detail.value,
  //     ['form.timeDate1']: e.detail.value,
  //   })
  // },


  //时间间隔数值变动
  bindSpaceChange: function (e) {
    var index = this.data.index
    this.setData({
      index: e.detail.value,
      ['form.time']: parseInt(e.detail.value) + 1
    })
  },


  //早上开始时间数值变动
  bindMornStartChange: function (e) {
     console.log()

    // console.log(e.detail.value)
    // console.log(this.data.moriningStart[e.detail.value])
    console.log(this.data.moriningStart[e.detail.value])
    this.setData({
      temp: []
    })
    for (var i = e.detail.value; i < this.data.moriningStart.length; i++) {
      this.data.temp.push(this.data.List[i])
    }
    
    this.setData({
      ['form.morningStartTime']: this.data.moriningStart[e.detail.value],
      indexMornS: e.detail.value,
      moriningEnd: this.data.temp,
      indexMorE: 0,

    })

  },


  bindMornendChange: function (e) {
    this.setData({
      ['form.morningEndTime']: this.data.moriningEnd[e.detail.value],
      indexMorE: e.detail.value
    })
  },


  //下午开始时间数值变动
  bindAftStartChange: function (e) {
    this.setData({
      temp1: []
    })
    for (var i = e.detail.value; i < this.data.afternoonStart.length; i++) {
      this.data.temp1.push(this.data.List1[i])
    }
    this.setData({
      ['form.afternoonStartTime']: this.data.afternoonStart[e.detail.value],
      indexAftS: e.detail.value,
      afternoonEnd: this.data.temp1,
      indexAftE: 0,
    })

  },

  bindAftendChange: function (e) {

    this.setData({
      ['form.afternoonEndTime']: this.data.afternoonEnd[e.detail.value],
      indexAftE: e.detail.value
    })

  },


  //  点击时间组件确定事件  
  bindTimeChange: function (e) {
    this.setData({
      times: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.getMessageList();
    setDate(this.data.year, this.data.month, this.data.day, this.data.year1, this.data.month1, this.data.day1, this)
    {
      var list = {
        url: '/system/dept/queryList',
        method: 'get',

      }
      APP.request.backWxRequest(list).then(res => {
        if (res.data.code === 200) {
          var rows =

            this.setData({
              deptList: res.data.rows[0]
            })
        }
      });
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(this.data.dateStart)
    console.log(this.data.dateend)
    // console.log(this.data.moriningStart)
    
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this
    that.setData({
      pageNum: that.data.pageNum + 1
    })
    // 获取预约数组
    that.getMessageList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //列表信息
  getMessageList() {
    var that = this
    that.setData({
      moriningStart: this.data.moriningStart,
      afternoonStart: this.data.afternoonStart,
      List: this.data.moriningStart,
      List1: this.data.afternoonStart
    })
    var tmp = this.data.moriningStart
    var tmp1 = this.data.afternoonStart

    var moriningEnd = tmp
    var afternoonEnd = tmp1
    that.setData({
      moriningEnd: moriningEnd,
      afternoonEnd: afternoonEnd
    })
 

    var list = {
      url: '/system/times/list?pageNum=' + this.data.pageNum + '&pageSize=' + this.data.pageSize,
      method: 'get',
      data: this.data.paramas
    }
    APP.request.backWxRequest(list).then(res => {
      if (res.data.code === 200) {
        console.log(res)
        var navList = this.data.navList
        var rows = res.data.rows
        var allArr = [...navList, ...rows]
        this.setData({
          navList: allArr
        })
        // console.log(this.data.navList)
      }
    });

  },

  xiugai(e) {
    console.log(e.currentTarget.dataset)
    this.setData({
      paramas: [],
      show: true,
      title: "修改信息",

    })
    var personList = {
      url: '/system/times/' + e.currentTarget.dataset.timesid,
      method: 'get',

    }
    APP.request.backWxRequest(personList).then(res => {
      if (res.data.code === 200) {
        // console.log(res.data.data)
        this.setData({
          num: 1,
          form: res.data.data,
          index: parseInt(res.data.data.time) - 1,

        });


      }
    });


  },

  shanchu(e) {
    let that = this
    // 确认框
    wx.showModal({
      title: '警告',
      content: '确认删除吗',
      success(res) {
      
        if (res.confirm) {
          // console.log('用户点击确定')
          var shanchuList = {
            url: '/system/times/' + e.currentTarget.dataset.timesid,
            method: 'delete',
          }
          APP.request.backWxRequest(shanchuList).then(res => {
            if (res.data.code === 200) {
              that.setData({
                pageNum: 1,
                pageSize: 4,
                navList: []
              })
              that.getMessageList();
            }
          });

        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
    // console.log(e.currentTarget.dataset)

  },

  tianjia() {
    this.setData({
      num: 2,
      form: [],
      // dateend: '',
      // dateStart: '',
      paramas: [],
      show: true,
      title: "添加信息",
    });
    this.setData({
      ['form.time']: this.data.index + 1
    })
  },
  //提交
  confirm() {
    var number1 = 0
    console.log(this.data.form.deptId)
    if (this.data.form.timesId != undefined) {
  

        if (this.data.form.morningStartTime != null && this.data.form.morningEndTime != null) {
          if (this.data.form.afternoonStartTime == null && this.data.form.afternoonEndTime == null) {
            number1 = 1
          }
          else
            if (this.data.form.afternoonStartTime != null && this.data.form.afternoonEndTime != null) {
              if (this.data.form.morningStartTime == null && this.data.form.morningEndTime == null) {
                number1 = 1
              }            
            }
        }
        if (this.data.form.afternoonStartTime != null && this.data.form.afternoonEndTime != null && this.data.form.morningStartTime != null && this.data.form.morningEndTime != null)
          number1 = 1
        if(number1 == 1)
        {
           this.setData({
          ['form.timeDate']: this.data.form.timeDate,
          ['form.timeDate1']: this.data.form.timeDate,
          });
        var personList = {
          url: '/system/times',
          method: 'put',
          data: this.data.form
        }
        APP.request.backWxRequest(personList).then(res => {
          if (res.data.code === 200) {
            this.setData({
              paramas: '',
              pageNum: 1,
              pageSize: 4,
              navList: []
            });
            this.getMessageList();
          }
        });
        } else {
          wx.showToast({
            title: '请选择完整时间',
            image: '../../assets/error.png',
          })
        }
    
    } else {
      if (!!!this.data.form.timeDate) {
        wx.showToast({
          title: '请选择开始日期',
          image: '../../assets/error.png',
        })
      } else
        if (!!!this.data.form.timeDate1) {
          wx.showToast({
            title: '请选择结束日期',
            image: '../../assets/error.png',
          })
        } else {
          if (this.data.form.morningStartTime != null && this.data.form.morningEndTime != null) {
            if (this.data.form.afternoonStartTime == null && this.data.form.afternoonEndTime == null) {
              number1 = 1
            }
            else
              if (this.data.form.afternoonStartTime != null && this.data.form.afternoonEndTime != null) {
                if (this.data.form.morningStartTime == null && this.data.form.morningEndTime == null) {
                  number1 = 1
                }
              }
          }
          if (this.data.form.afternoonStartTime != null && this.data.form.afternoonEndTime != null && this.data.form.morningStartTime != null && this.data.form.morningEndTime != null)
            number1 = 1
          if (number1 == 1) {
            this.setData({
              ['form.timeDate']: this.data.form.timeDate,
              ['form.timeDate1']: this.data.form.timeDate1,
            });
            var personList = {
              url: '/system/times',
              method: 'post',
              data: this.data.form
            }
            APP.request.backWxRequest(personList).then(res => {
              if (res.data.code === 200) {
                this.setData({
                  paramas: '',
                  pageNum: 1,
                  pageSize: 4,
                  navList: []
                });
                this.getMessageList();
              }
            });
          } else {
            wx.showToast({
              title: '请选择完整时间',
              image: '../../assets/error.png',
            })
          }
        }
    }
  },

})